from rest_framework import serializers

from test1.models import Bepartment, User


class BepartmentSerializer(serializers.ModelSerializer):
    """部门序列化器"""
    # id = serializers.IntegerField(label='id', read_only=True)  # 序列化时用到，反序列化忽略
    # name = serializers.CharField(label='部门名', max_length=30)  # 限制长度不超过30
    # create_date = serializers.DateField(label='创建时间')

    class Meta:
        model = Bepartment
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    """员工序列化器"""
    # id = serializers.IntegerField(label='id', read_only=True)
    # name = serializers.CharField(label='姓名', max_length=30)
    # age = serializers.IntegerField(label='年龄')

    # bepartment = serializers.SlugRelatedField(label='部门名', read_only=True, slug_field='name')  # 只能读不能写
    # bepartment = BepartmentSerializer(many=True, read_only=True)  # X
    # bepartment = serializers.SerializerMethodField()  # 只能读不能写
    bepartment_name = serializers.ReadOnlyField(source='bepartment.name')  # ok

    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {  # 限制
            'bepartment': {
                'write_only': True  # 只在写入是使用，读取时不显示
                }
            }

    # def get_bepartment(self, obj):  # get_子段名   与第三个一起使用
    #     return obj.bepartment.name

